#!/usr/bin/env python
# -*- coding:utf-8 -*-
from urllib.parse import urlencode,parse_qs
from django.conf import settings
from urllib.request import urlopen
import json
class OauthQQTool(object):

    def get_oauth_url(self):

        base_url = "https://graph.qq.com/oauth2.0/authorize?"

        params = {
            "response_type": "code",
            "client_id": settings.QQ_APP_ID,
            "redirect_uri": settings.QQ_REDIRECT_URL,
            "state": "/"
        }

        url = base_url + urlencode(params)

        return url

    def get_access_token_by_url(self,code):
        base_url = 'https://graph.qq.com/oauth2.0/token?'

        params = {
            'grant_type': 'authorization_code',
            'client_id': settings.QQ_APP_ID,
            'client_secret': settings.QQ_APP_KEY,
            'code': code,
            'redirect_uri': settings.QQ_REDIRECT_URL
        }

        url = base_url + urlencode(params)

        # 通过url获取token
        response = urlopen(url)

        data = response.read().decode()

        access_data = parse_qs(data)

        access_token = access_data.get("access_token")[0]

        return access_token

    def get_openid_by_token(self,access_token):
        """
            1 请求地址
            PC网站：https://graph.qq.com/oauth2.0/me

            2 请求方法
            GET

            3 请求参数
            请求参数请包含如下内容：

            参数	是否必须	含义
            access_token	必须	在Step1中获取到的access token。
        """
        base_url = "https://graph.qq.com/oauth2.0/me?"

        params = {
            'access_token':access_token
        }
        url = base_url + urlencode(params)

        response = urlopen(url)
        try:
            data = response.read().decode()[10:-4]
        except Exception:
            raise Exception("数据获取失败")

        openid = json.loads(data).get("openid")

        return openid



# 'callback( {"client_id":"101474184","openid":"C84F374B3E7305D3C6974B1CBB935756"} );
